<template>
  <div class="tab-content">
    <div class="header-section">
      <div class="title-section">
        <h2>登录记录</h2>
        <span class="subtitle">查看设备的登录记录</span>
      </div>
      <div class="action-section">
        <el-button type="primary" @click="fetchLoginRecords" :loading="loadingLoginRecords">
          <el-icon><Refresh /></el-icon>刷新
        </el-button>
      </div>
    </div>

    <el-card class="record-card">
      <div class="table-wrapper" v-loading="loadingLoginRecords">
        <el-table
          :data="loginRecords"
          style="width: 100%"
          border
        >
          <el-table-column prop="equipment_name" label="设备名称" width="180" />
          <el-table-column prop="auth" label="状态" width="100">
            <template #default="{ row }">
              <el-tag :type="getStatusType(row.auth)">{{ row.auth }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="equipment_time" label="时间" width="180" />
          <el-table-column prop="equipment_description" label="描述" />
        </el-table>

        <div class="pagination-wrapper" style="margin-top: 20px; text-align: right;">
          <el-pagination
            v-model:current-page="currentPage"
            v-model:page-size="pageSize"
            :page-sizes="[10, 20, 50, 100]"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, computed, watch } from 'vue'
import { ElMessage } from 'element-plus'
import { Refresh } from '@element-plus/icons-vue'

const props = defineProps({
  currentDevice: {
    type: Object,
    required: true
  }
})

// 登录记录相关数据
const allLoginRecords = ref([])
const loginRecords = ref([])
const loadingLoginRecords = ref(false)
const currentPage = ref(1)
const pageSize = ref(20)
const total = ref(0)

// 更新当前页数据
const updateCurrentPageData = () => {
  const start = (currentPage.value - 1) * pageSize.value
  const end = start + pageSize.value
  loginRecords.value = allLoginRecords.value.slice(start, end)
}

// 获取登录记录
const fetchLoginRecords = async () => {
  if (!props.currentDevice) {
    ElMessage.warning('请先选择设备')
    return
  }
  loadingLoginRecords.value = true
  try {
    const token = localStorage.getItem('token')
    // 使用设备的device_number作为deviceId
    const deviceNumber = props.currentDevice.device_number || props.currentDevice.id.toString()
    if (!deviceNumber) {
      throw new Error('无效的设备ID')
    }
    const params = new URLSearchParams({
      page: currentPage.value.toString(),
      page_size: pageSize.value.toString(),
      device_number: deviceNumber
    })
    const response = await fetch(`https://penglink.pcwxcn.top/api/equipment`, {
      headers: {
        'Authorization': `Bearer ${token}`,
        'Accept': 'application/json'
      }
    })
    if (!response.ok) {
      throw new Error('获取登录记录失败')
    }
    const result = await response.json()
    if (result.code === 200) {
      // 筛选当前设备的记录并按时间倒序排序
      allLoginRecords.value = result.data
        .filter(record => 
          record.equipment_name === props.currentDevice.equipment_name &&
          (record.auth === '上线' || record.auth === '下线')
        )
        .sort((a, b) => new Date(b.equipment_time) - new Date(a.equipment_time))
      
      // 更新总数
      total.value = allLoginRecords.value.length

      // 更新当前页数据
      updateCurrentPageData()
    } else {
      throw new Error(result.message || '获取登录记录失败')
    }
  } catch (error) {
    ElMessage.error(error.message)
    allLoginRecords.value = []
    loginRecords.value = []
    total.value = 0
  } finally {
    loadingLoginRecords.value = false
  }
}

// 处理页码变化
const handleCurrentChange = (val) => {
  currentPage.value = val
  updateCurrentPageData()
}

// 处理每页条数变化
const handleSizeChange = (val) => {
  pageSize.value = val
  currentPage.value = 1 // 重置到第一页
  updateCurrentPageData()
}

// 监听设备变化，重新获取数据
watch(() => props.currentDevice, (newDevice) => {
  if (newDevice) {
    currentPage.value = 1 // 重置页码
    fetchLoginRecords()
  } else {
    allLoginRecords.value = []
    loginRecords.value = []
    total.value = 0
  }
}, { immediate: true })

// 获取状态标签类型
const getStatusType = (status) => {
  return status === '上线' ? 'success' : 'danger'
}
</script>

<style scoped>
.tab-content {
  padding: 20px;
}

.header-section {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.title-section {
  display: flex;
  flex-direction: column;
}

.title-section h2 {
  margin: 0;
  font-size: 1.5rem;
  color: #303133;
}

.subtitle {
  color: #909399;
  font-size: 0.9rem;
  margin-top: 5px;
}

.action-section {
  display: flex;
  gap: 10px;
  align-items: center;
}

.record-card {
  margin-bottom: 20px;
}

.table-wrapper {
  min-height: 300px;
}

.pagination-wrapper {
  margin-top: 20px;
  text-align: right;
}
</style>